package filter

import (
	"strings"

	"file_explorer/common/consts"
	"file_explorer/common/util"
	"file_explorer/model"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/widget"
)

type FileTypeFilter struct {
	checkGroup *widget.CheckGroup
}

func (filter *FileTypeFilter) GetCanvasObject() fyne.CanvasObject {
	return filter.checkGroup
}

func (filter *FileTypeFilter) Filter(fileInfo *model.FileInfo) bool {
	return util.InStrArray(fileInfo.GetTypeStr(), filter.checkGroup.Selected) >= 0
}

func (filter *FileTypeFilter) GetValue() string {
	return strings.Join(filter.checkGroup.Selected, ",")
}

func (filter *FileTypeFilter) LoadValue(val string) {
	filter.checkGroup.Selected = strings.Split(val, ",")
	filter.checkGroup.Refresh()
}

func (filter *FileTypeFilter) Reset() {
	filter.checkGroup.Selected = []string{consts.FileTypeStrRegular, consts.FileTypeStrDir}
	filter.checkGroup.Refresh()
}

func NewFileTypeFilter(onChange func()) *FileTypeFilter {
	checkList := []string{consts.FileTypeStrRegular, consts.FileTypeStrDir}
	filter := &FileTypeFilter{
		checkGroup: widget.NewCheckGroup(checkList, nil),
	}
	filter.checkGroup.SetSelected(checkList)
	filter.checkGroup.Horizontal = true
	filter.checkGroup.OnChanged = func(_ []string) {
		onChange()
	}

	return filter
}
